package com.lovecws.mumu.controller.system.role;

import com.lovecws.mumu.common.core.enums.PublicEnum;
import com.lovecws.mumu.common.core.response.ResponseEntity;
import com.lovecws.mumu.common.core.tree.ZTreeBean;
import com.lovecws.mumu.shiro.realm.UserRealm;
import com.lovecws.mumu.system.entity.SysMenu;
import com.lovecws.mumu.system.entity.SysPermission;
import com.lovecws.mumu.system.service.SysMenuService;
import com.lovecws.mumu.system.service.SysPermissionService;
import com.lovecws.mumu.system.service.SysRolePermissionService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/system/role")
public class RolePermissionController {

	private static final Logger log=Logger.getLogger(RolePermissionController.class);
	@Autowired
	private SysRolePermissionService rolePermissionService;
	@Autowired
	private SysPermissionService permissionService;
	@Autowired
	private SysMenuService menuService;
	@Autowired
	private UserRealm userRealm;
	
	/**
	 * 用户分配权限
	 * @return
	 */
	@RequiresPermissions("system:role:allowPermission")
	@RequestMapping(value = { "/allowPermission" }, method = RequestMethod.GET)
	public String allowRole(String roleId,HttpServletRequest request) {
		request.setAttribute("roleId", roleId);
		return "system/role/allowPermission";
	}

	/**
	 * 角色权限列表列表
	 * @param roleId 角色id
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("system:role:allowPermission")
	@RequestMapping(value = { "/rolePermission/{roleId}" }, method = RequestMethod.GET)
	public List<ZTreeBean> roleMenu(@PathVariable String roleId) {
		// 获取当前角色下的菜单
		List<SysMenu> selectedMenus = menuService.getSysMenuByRoleId(roleId, PublicEnum.NORMAL.value());
		// 获取所有的权限
		List<SysPermission> allPermissions = permissionService.querySysPermissionByCondition(null, null, null,PublicEnum.NORMAL.value());
		// 获取当前角色下的权限
		List<SysPermission> selectedPermissions = permissionService.getSysPermissionByRoleId(roleId,PublicEnum.NORMAL.value());
		// ztree 权限树树
		List<ZTreeBean> ztree = new ArrayList<ZTreeBean>();
		// ztree菜单树
		for (SysMenu sysMenu : selectedMenus) {
			if(sysMenu.getParentMenuId()==0){
				ztree.add(new ZTreeBean(sysMenu.getMenuId().toString(), "topPermission", sysMenu.getMenuName(), true, sysMenu.getMenuIcon(), true));
			}else{
				ztree.add(new ZTreeBean(sysMenu.getMenuId().toString(), sysMenu.getParentMenuId().toString(),sysMenu.getMenuName(), true, sysMenu.getMenuIcon(), true));
			}

			for (SysPermission sysPermission : allPermissions) {
				// 找到菜单下的权限
				if (sysPermission.getMenuId() == sysMenu.getMenuId()) {
					// 在判断这个权限是否被选中
					Integer permissionId = sysPermission.getPermissionId();
					boolean flag = false;
					for (SysPermission selectedPermission : selectedPermissions) {
						if (selectedPermission.getPermissionId() == permissionId) {
							flag = true;
							break;
						}
					}
					ztree.add(new ZTreeBean("p"+permissionId.toString(), sysPermission.getMenuId().toString(),sysPermission.getPermissionName(), true, null, flag));
				}
			}
		}
		ztree.add(new ZTreeBean("topPermission", "0", "权限树", true, "", "", false));
		return ztree;
	}
	
	/**
	 * 保存角色权限
	 * @param roleId 角色id
	 * @param permissionIds 权限id（多条以逗号隔开）
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("system:role:allowPermission")
	@RequestMapping(value={"/rolePermission"},method=RequestMethod.POST)
	public ResponseEntity saveRolePermission(String roleId, String permissionIds){
		try {
			rolePermissionService.saveRolePermission(roleId,permissionIds,SecurityUtils.getSubject().getPrincipal().toString());
			userRealm.clearPermissionCache(null);
		} catch (Exception e) {
			log.error(e);
			new ResponseEntity(500, "保存角色权限出现异常", null);
		}
		return new ResponseEntity(200,"角色分配权限操作成功",null);
	}
}
